package com.yyk.yykywd.mvvm.ui

import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.Observer
import com.orhanobut.logger.Logger
import com.yyk.yykywd.*
import com.yyk.yykywd.config.HttpUrl
import com.yyk.yykywd.mvvm.base.LoadRegionData
import com.yyk.yykywd.mvvm.event.FinishWorkDetail
import com.yyk.yykywd.mvvm.view_model.AddCustomerViewModel
import com.yyk.yykywd.mvvm.view_model.WorkDetailViewModel
import com.yyk.yykywd.util.TimeUtil
import com.yyk.yykywd.util.ToAnotherActivity
import com.yyk.yykywd.util.ToastUtil
import kotlinx.android.synthetic.main.activity_claim_customer.*
import kotlinx.android.synthetic.main.rl_bottom.*
import org.greenrobot.eventbus.EventBus

class ClaimCustomerActivity : LoadRegionData() {
    private lateinit var workDetailViewModel: WorkDetailViewModel
    private lateinit var addCustomerViewModel: AddCustomerViewModel

    override fun initData() {
        workDetailViewModel.getReturnMoneyDetail()
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_claim_customer
    }

    override fun initView() {
        workDetailViewModel = getViewModel(this, WorkDetailViewModel::class.java)
        addCustomerViewModel = getViewModel(this, AddCustomerViewModel::class.java)
        with(workDetailViewModel) {
            id = intent.getStringExtra(ID)
            type = intent.getStringExtra(TYPE)
            if (type == FROM_CUSTOMER_OPEN_SEA_AGENT) {
                cl_agent1.visibility = View.VISIBLE
                cl_agent2.visibility = View.VISIBLE
                cl_hospital1.visibility = View.GONE
                cl_hospital2.visibility = View.GONE
                iv.setImageResource(R.drawable.icon_dls1)
                //加载省市级选择器
                mHandler.sendEmptyMessage(MSG_LOAD_DATA)
            } else {
                cl_hospital1.visibility = View.VISIBLE
                cl_hospital2.visibility = View.VISIBLE
                cl_agent1.visibility = View.GONE
                cl_agent2.visibility = View.GONE
                iv.setImageResource(R.drawable.icon_yy1)
            }
            addCustomerViewModel.getType()
        }

        setBackArrow {
            backLogic(mActivity) {
                finish()
            }
        }
        setTitle("认领客户")
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backLogic(mActivity) {
                finish()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun setListener() {
        super.setListener()
        cl_business_process_tracking.setOnClickListener {
            var t = ""
            with(workDetailViewModel.type) {
                if (this == FROM_CUSTOMER_OPEN_SEA_AGENT) {
                    t = "2"
                } else {
                    t = "1"
                }
            }
            val url = String.format(HttpUrl.BUSINESS_PROCESS_TRACKING, workDetailViewModel.id, t)
            ToAnotherActivity.toWebActivity(mActivity, url, "业务流程跟踪")
        }

        tv_execute.setOnClickListener {
            if (required()) {
                return@setOnClickListener
            }

            show(mActivity, "是否确认认领客户？",
                    "保存后，可在\"工作-意向客户\"中跟进此客户",
                    "确认",
                    "取消") {
                if (workDetailViewModel.type == FROM_CUSTOMER_OPEN_SEA_AGENT) {
                    var source = ""
                    source = if (getTextString(tv_agent_source) == "其他") {
                        getTextString(et_source)
                    } else {
                        getTextString(tv_agent_source)
                    }
                    addCustomerViewModel.claimAgentCustomer(workDetailViewModel.id,
                            getTextString(et_contact),
                            getTextString(tv_agent_region),
                            source,
                            getTextString(et_agent_industry),
                            getTextString(et_agent_describe))
                } else {
                    addCustomerViewModel.claimHospitalCustomer(workDetailViewModel.id,
                            getTextString(tv_hospital_type),
                            getTextString(tv_hospital_rating),
                            transToTimeStamp(getTextString(tv_visit_time), TimeUtil.YYYY_MM_DD).toString(),
                            getTextString(et_visit_name),
                            getTextString(et_visit_phone),
                            getTextString(et_visitor_position),
                            getTextString(et_hospital_situation))
                }
            }
        }

        workDetailViewModel.hospitalDetail.observe(this, Observer {
            it.data?.run {
                tv_status.text = tag_client
                tv_number.text = operation_num
                tv_founder.text = addname
                tv_create_time.text = getCommonTime(create_time)
                tv_throw_sea_time.text = getCommonTime(cast_time)
                tv_hospital_name.text = hos_name
                tv_hospital_type.text = type_name
                tv_hospital_rating.text = grade_name
                tv_visit_time.text = getCommonTimeWithYMD(call_time)
                et_visit_name.setText(call_name)
                et_visit_name.setSelection(call_name.length)
                et_visitor_position.setText(call_grade)
                et_visit_phone.setText(call_phone)
                et_hospital_situation.setText(hos_text)
            }
        })

        workDetailViewModel.agentDetail.observe(this, Observer {
            it.data?.run {
                tv_status.text = tag_client
                tv_number.text = operation_num
                tv_founder.text = addname
                tv_create_time.text = getCommonTime(create_time)
                tv_throw_sea_time.text = getCommonTime(cast_time)
                if (ptype == 2) {
                    tv_agent_type.text = "个人"
                } else {
                    tv_agent_type.text = "公司"
                }
                et_agent_name.text = agentname
                et_contact.setText(phone)
                et_contact.setSelection(phone.length)
                tv_agent_region.text = area
                tv_agent_source.text = source
                et_agent_industry.setText(trade)
                et_agent_describe.setText(desc)
            }
        })

        tv_agent_region.setOnClickListener {
            if (isLoaded) {
                showPickerView()
            }
        }

        tv_agent_source.setOnClickListener {
            val showOptionsPicker = showOptionsPicker(mActivity) { options1: Int, _: Int, _: Int ->
                tv_agent_source.text = addCustomerViewModel.agentSource[options1]
                if (getTextString(tv_agent_source) == "其他") {
                    cl_source.visibility = View.VISIBLE
                } else {
                    cl_source.visibility = View.GONE
                }
            }
            showOptionsPicker.setSelectOptions(0, 0, 0)
            showOptionsPicker.setPicker(addCustomerViewModel.agentSource) //三级选择器
            showOptionsPicker.show()
        }

        tv_visit_time.setOnClickListener {
            showTimePicker(mActivity,
                    showYear = true,
                    showMonth = true,
                    showDay = true,
                    showHour = false,
                    showMinute = false,
                    showSecond = false,
                    startDate = addCustomerViewModel.startDate,
                    endDate = addCustomerViewModel.endDate,
                    pattern = TimeUtil.YYYY_MM_DD) {
                tv_visit_time.text = it
            }
        }

        tv_hospital_type.setOnClickListener {
            val showOptionsPicker = showOptionsPicker(mActivity) { options1: Int, _: Int, _: Int ->
                tv_hospital_type.text = addCustomerViewModel.hospitalType[options1]
            }
            showOptionsPicker.setSelectOptions(0, 0, 0)
            showOptionsPicker.setPicker(addCustomerViewModel.hospitalType) //三级选择器
            showOptionsPicker.show()
        }

        tv_hospital_rating.setOnClickListener {
            val showOptionsPicker = showOptionsPicker(mActivity) { options1: Int, _: Int, _: Int ->
                tv_hospital_rating.text = addCustomerViewModel.hospitalGrade[options1]
            }
            showOptionsPicker.setSelectOptions(0, 0, 0)
            showOptionsPicker.setPicker(addCustomerViewModel.hospitalGrade) //三级选择器
            showOptionsPicker.show()
        }

        addCustomerViewModel.base.observe(this, Observer {
            ToastUtil.showShort(it.msg)
            if (it.code == 200) {
                EventBus.getDefault().post(FinishWorkDetail())
                finish()
            }
        })
    }

    private fun required(): Boolean {
        if (workDetailViewModel.type == FROM_CUSTOMER_OPEN_SEA_AGENT) {
            if (getTextString(et_contact).isBlank()) {
                ToastUtil.showShort("请填写联系方式")
                return true
            }
            if (getTextString(tv_agent_source) == "其他" && getTextString(et_source).isBlank()) {
                ToastUtil.showShort("请填写代理商来源")
                return true
            }
        } else {
            if (getTextString(et_visit_name).isBlank()) {
                ToastUtil.showShort("请填写拜访人姓名")
                return true
            }
            if (getTextString(et_visitor_position).isBlank()) {
                ToastUtil.showShort("请填写拜访人职位")
                return true
            }
            if (getTextString(et_visit_phone).isBlank()) {
                ToastUtil.showShort("请填写拜访人电话")
                return true
            }
            if (getTextString(et_hospital_situation).isBlank()) {
                ToastUtil.showShort("请填写医院情况")
                return true
            }
        }
        return false
    }

    private fun showPickerView() { // 弹出选择器
        val pvOptions = showOptionsPicker(mActivity) { options1: Int, options2: Int, options3: Int ->
            val tx = options1Items[options1].pickerViewText.toString() + "—" +
                    options2Items[options1][options2]
            tv_agent_region.text = tx
            province_id = index1Items[options1].name_id
            city_id = index2Items[options1][options2]
            county_id = index3Items[options1][options2][options3]
            Logger.e("省市区$province_id,$city_id,$county_id")
        }
        pvOptions.setSelectOptions(0, 0, 0)
//        pvOptions.setPicker(options1Items as List<Any>, options2Items as List<MutableList<Any>>?, options3Items as List<MutableList<MutableList<Any>>>) //三级选择器
        pvOptions.setPicker(options1Items as List<Any>, options2Items as List<MutableList<Any>>?, null) //三级选择器
        pvOptions.show()
    }
}
